﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using mmCore.Common;
using mmCore.Interfaces;

namespace mmImdbProvider
{
    public class ImdbSearch: ISearchable<SearchMovieResult>
    {
        #region EVENTS

        public event Action<List<SearchMovieResult>> OnFound;
        public event Action<SearchMovieResult> OnSearchProgress;

        #endregion EVENTS

        #region METHODS

        public bool Search(string strSearch)
        {
            if(string.IsNullOrEmpty(strSearch))
            {
                return false;
            }

            var wf = new WebFetch(MovieUtils.GetSearchUrl(strSearch));
            wf.OnFinished += wf_OnFinished;
            wf.Fetch();

            return true;
        }

        #endregion METHODS

        #region PRIVATE

        private void wf_OnFinished(object sender, FetchEventArgs e)
        {
            const string strReg = "<tr class=\"even detailed\">[\\d\\D]*?<img src=\"(http://ia.media-[\\d\\D]*?jpg)\"[\\d\\D]*?></a>[\\n\\r\\s]*?</td>[\\n\\r\\s]*?<td class=\"title\">[\\d\\D]*?<a href=\"/title/tt(\\d{7})/\">([\\D\\d]*?)</a>[\\d\\D]*?<span class=\"year_type\">\\(([\\d\\D]*?) [\\D\\d]*?\\)</span>";
            var lstResult = new List<SearchMovieResult>();

            try
            {
                var rRegex = new Regex(strReg, RegexOptions.Multiline);
                var mMatch = rRegex.Match(e.Result);
                var strLastTitle = string.Empty;
                
                while (mMatch.Success)
                {
                    if (mMatch.Groups[3].Value == strLastTitle)
                    {
                        mMatch = mMatch.NextMatch();
                        continue;
                    }
                    strLastTitle = HttpUtility.HtmlDecode(mMatch.Groups[3].Value);
                    var smr = new SearchMovieResult
                    {
                        CoverUrl = mMatch.Groups[1].Value,
                        Id = mMatch.Groups[2].Value,
                        Title = strLastTitle,
                        Year = mMatch.Groups[4].Value
                    };
                    lstResult.Add(smr);
                    if (OnSearchProgress != null)
                    {
                        OnSearchProgress(smr);
                    }
                    mMatch = mMatch.NextMatch();
                }
            }
            catch(Exception ex)
            {
                ExceptionManager.ReportError(ex);
                if (OnFound != null)
                {
                    OnFound(null);
                }
            }

            if(OnFound != null)
            {
                OnFound(lstResult);
            }
        }

        #endregion PRIVATE
    }
}
